package com.qt.myboot.aspect;

import com.qt.myboot.annotation.Retry;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Despription:
 *
 * @Autor: xusl
 * @Date: 2019/6/13 19:24
 * @Version: 1.0
 **/
@Aspect
@Component
@Slf4j
public class RetryAspect {


    @Pointcut("@annotation(com.qt.myboot.annotation.Retry)")
    public void retryPointCut() {

    }

    @Around("retryPointCut()")
    public Object retry(ProceedingJoinPoint pjp) {
        Method method = ((MethodSignature) pjp.getSignature()).getMethod();
        Retry retry = method.getAnnotation(Retry.class);
        int retries = retry.retries();
        int num = 0;
        do {
            num++;
            try {
                return pjp.proceed();
            } catch (Throwable throwable) {
                if (num > retries) {
                    log.info("重试 {}", num, "次失败");
                    throw new RuntimeException("重试" + num + "次失败");
                } else {
                    log.info("=====正在重试=====" + num + "次");
                }
            }

        } while (num <= retries);
        return null;
    }
}
